package servlet;

import util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;


@WebServlet(urlPatterns = "/AddUserServlet.do")
public class AddUserServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");


        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userType = request.getParameter("userType");
        int role=Integer.parseInt(userType);
        if (is_register(username)) { // 检查用户名是否已注册
            boolean registrationSuccess = register(username, password,role);
            if (registrationSuccess) {
                // 注册成功，重定向到注册成功页面
                response.sendRedirect("usermanager/success.jsp");
            } else {
                // 注册失败，重定向到错误页面
                response.sendRedirect("errorPage.jsp");
            }
        } else {
            // 用户名已存在，重定向到提示页面
            response.sendRedirect("errorPage1.jsp");
        }

    }

    private boolean is_register(String username) {
        JDBCUtil jdbcUtil = new JDBCUtil();
        String sql = "select * from 02_38_yangyang where username=? ";
        ResultSet resultSet = jdbcUtil.prepareQuery(sql, username);

        try {

            if (!resultSet.next()) {
                // 登录成功
                return true;
            } else {
                // 登录失败，账号不存在

                return false;
            }
        } catch (SQLException e) {
            // 处理异常
            e.printStackTrace();
            return false; // 或者抛出自定义异常
        } finally {
            // 关闭数据库资源
            jdbcUtil.closeConnection();
        }
    }

    public boolean register(String username, String password ,int role) {
        JDBCUtil jdbcUtil = new JDBCUtil();
        String sql = "INSERT INTO 02_38_yangyang(username, password,role) VALUES (?,?,?)";

        // 执行插入操作，传入参数并获取操作结果
        boolean registrationSuccess = jdbcUtil.update(sql, username, password,role);

        // 返回操作结果
        return registrationSuccess;
    }
}

